//
//  PCUserViewController.m
//  PhotoCircle
//
//  Created by GL on 15/12/10.
//  Copyright © 2015年 wujungao. All rights reserved.
//

#import "PCUserViewController.h"
#import "PCMeCommonCell.h"
#import "PCMeCommonLineCell.h"
#import "PCMeHeaderCell.h"
#import "PCMeLogoutCell.h"
#import "PCMeStore.h"
#import "PCUserModel.h"
#import "PCJoinPhotoMatchVC.h"
#import "PCPhotoUploadVC.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>

@interface PCUserViewController ()<UITableViewDataSource,UITableViewDelegate,PCMeHeaderCellDelegate,PCLogoutCellDelegate,UIAlertViewDelegate,PlusDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) PCUserModel *userModel;

@end

@implementation PCUserViewController

-(PCUserModel*)userModel
{
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
        _userModel = [[PCUserInfoManager sharedUserInfo] readUserInfo];
    }else{
        _userModel = nil;
    }
    return _userModel;
}

-(void)initData
{
    NSDictionary *pDic = @{@"token":self.userModel.userToken};
    __weak PCUserViewController *weakSelf = self;
    [[PCMeStore sharedMeStore] requestUserListDataWith:pDic successHandler:^(NSInteger responCode){
        if (responCode == API_RESPONSE_OK) {
            [weakSelf.tableView reloadData];
        }
    } errorHandler:^{
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //[self logoutSheying];
    //[[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    MCShowPlusBackgroundView();
    MCPlusDelegate();
    
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
        [self initData];
    }
    
    [self.tableView reloadData];
    MCShowBottomView();
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIImage *)getImageForIconWithSetion:(NSInteger)section row:(NSInteger)row
{
//    PCMeAbout
//    PCMeAlbum
//    PCMeFeedback
//    PCMeMatch
    UIImage *iconImg;
    if (section == 1) {
        if (row ==0) {
            iconImg = [UIImage imageNamed:@"PCMeAlbum"];
            return iconImg;
        }else{
            iconImg = [UIImage imageNamed:@"PCMeMatch"];
            return iconImg;
        }
    }else if (section == 2){
        if (row == 0) {
            iconImg = [UIImage imageNamed:@"PCMeFeedback"];
            return iconImg;
        }else{
            iconImg = [UIImage imageNamed:@"PCMeAbout"];
            return iconImg;
        }
    }else{
        return nil;
    }
}

-(NSString *)getTitleWithSetion:(NSInteger)section row:(NSInteger)row
{
    NSString *titleString;
    if (section == 1) {
        if (row ==0) {
            titleString = @"我的个人相册";
            return titleString;
        }else{
            titleString = @"我的参赛";
            return titleString;
        }
    }else if (section == 2){
        if (row == 0) {
            titleString = @"给摄影圈提意见";
            return titleString;
        }else{
            titleString = @"关于";
            return titleString;
        }
    }else{
        return nil;
    }
}

- (IBAction)clickHeaderImageView:(UITapGestureRecognizer *)sender {
    
    if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
        [self performSegueWithIdentifier:@"pushUserInfiVC" sender:self];
    }else{
        [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
    }
    //NSLog(@"clickHeaderImageView");
}

- (IBAction)clickUserName:(UITapGestureRecognizer *)sender {
    
    // 点击登录
    if (![[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
        [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
    }
    NSLog(@"点击登录");
}

#pragma mark -
#pragma mark - UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 2;
    }else{
        if ([[PCUserInfoManager sharedUserInfo] checkUserInfo]) {
            return 3;
        }else{
            return 2;
        }
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //MeCommonCell
    //MeCommonLineCell
    //MeHeaderCell
    //MeLogoutCell
    
    if (indexPath.section == 0) {
        static NSString *questionCellID = @"MeHeaderCell";
        PCMeHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
        cell.delegate = self;
        [cell configCellWithUserModel:self.userModel];
        return cell;

    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            static NSString *questionCellID = @"MeCommonLineCell";
            PCMeCommonLineCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
            UIImage *iconImg = [self getImageForIconWithSetion:indexPath.section row:indexPath.row];
            NSString *title = [self getTitleWithSetion:indexPath.section row:indexPath.row];
            [cell configCellWithIcon:iconImg title:title];
            if (self.userModel) {
                [cell configCellWithCount:self.userModel.userAlbumCount];
            }
            return cell;
        }else{
            static NSString *questionCellID = @"MeCommonCell";
            PCMeCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
            UIImage *iconImg = [self getImageForIconWithSetion:indexPath.section row:indexPath.row];
            NSString *title = [self getTitleWithSetion:indexPath.section row:indexPath.row];
            [cell configCellWithIcon:iconImg title:title];
            if (self.userModel) {
                [cell configCellWithCount:self.userModel.userGameCount];
            }
            return cell;
        }
    }else{
        if (indexPath.row == 0) {
            static NSString *questionCellID = @"MeCommonLineCell";
            PCMeCommonLineCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
            UIImage *iconImg = [self getImageForIconWithSetion:indexPath.section row:indexPath.row];
            NSString *title = [self getTitleWithSetion:indexPath.section row:indexPath.row];
            [cell configCellWithIcon:iconImg title:title];
            return cell;

        }else if (indexPath.row == 1){
            static NSString *questionCellID = @"MeCommonCell";
            PCMeCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
            UIImage *iconImg = [self getImageForIconWithSetion:indexPath.section row:indexPath.row];
            NSString *title = [self getTitleWithSetion:indexPath.section row:indexPath.row];
            [cell configCellWithIcon:iconImg title:title];
            return cell;
        }else{
            static NSString *questionCellID = @"MeLogoutCell";
            PCMeLogoutCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
            cell.delegate = self;
            return cell;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            if([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
                // 个人相册
                [self performSegueWithIdentifier:@"pushUserAlbumVC" sender:self];
            }else{
                [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
            }
        }else{
            if([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
                // 个人参赛
                [self performSegueWithIdentifier:@"pushUserGameVC" sender:self];
            }else{
                [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
            }
        }
    }else if (indexPath.section == 2){
        if (indexPath.row ==0) {
            if([[PCUserInfoManager sharedUserInfo] checkUserInfo]){
                // 意见反馈
                [self performSegueWithIdentifier:@"pushToFeedbackVC" sender:self];
            }else{
                [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
            }
        }else if(indexPath.row == 1){
            // 关于
            [self performSegueWithIdentifier:@"pushToAboutVC" sender:self];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1 || section == 2) {
        return 10;
    }
    return 0.001;
}



-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1 || section == 2) {
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
        headerView.backgroundColor = [UIColor colorWithRed:246.0/255.0 green:246.0/255.0 blue:246.0/255.0 alpha:1.0];
        return headerView;
    }else {
        return nil;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 190;
    }else if (indexPath.section == 1){
        return 50;
    }else{
        if (indexPath.row == 2) {
            return 100;
        }else{
            return 50;
        }
    }
}

#pragma mark -
#pragma mark -PCMeHeaderCellDelegate
-(void)selectedLogin
{
    // 登录
    NSLog(@"selectedLogin");
    [self performSegueWithIdentifier:@"pushLoginVC" sender:self];
}

-(void)selectedRegister
{
    // 注册
    NSLog(@"selectedRegister");
    //mePushToRegisterVC
    [self performSegueWithIdentifier:@"pushRegisterVC" sender:self];
}

#pragma mark -
#pragma mark -PCLogoutCellDelegate
-(void)logout
{
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否退出登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self logoutSheying];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
            
        }];
        
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否退出登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        [cancleAlert show];
    }
}

-(void)logoutSheying{
    // 退出登录
    [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
    [[PCMeStore sharedMeStore] clearUserInfo];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark -PCLogoutCellDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self logoutSheying];
    }else{
        
    }
}

#pragma mark - plusDelegate
-(void)joinPhotoMatch{
    //拍照上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

-(void)albumUpload{
    //参赛
    UIStoryboard *joinStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCJoinPhotoMatchVC *joinVC=[joinStory instantiateViewControllerWithIdentifier:@"PCJoinPhotoMatchVC"];
//    [joinVC passVCType:meVC];
    [self.navigationController pushViewController:joinVC animated:YES];
    simulationPressPlusBtn();
}

-(void)photoGraphUpload{
    //相册上传
    UIImagePickerController *imagePickerVC=[[UIImagePickerController alloc] init];
    imagePickerVC.delegate=self;
    imagePickerVC.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:imagePickerVC animated:YES completion:nil];
}

#pragma mark - image picker delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *imageURL=[info objectForKey:UIImagePickerControllerReferenceURL];
    __block NSDictionary *metadataDict;
    
    if(picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){
        //相册
        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
            ALAssetRepresentation *representation = [myasset defaultRepresentation];
            metadataDict=representation.metadata;
            
            //upload图片
            [self uploadImage:image withImageMetaData:metadataDict];
        };
        
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
        [assetslibrary assetForURL:imageURL
                       resultBlock:resultblock
                      failureBlock:nil];
        
    }else{
        //拍照
        metadataDict=[info valueForKey:UIImagePickerControllerMediaMetadata];
        //upload图片
        [self uploadImage:image withImageMetaData:metadataDict];
    }
}

-(void)uploadImage:(UIImage *)image withImageMetaData:(NSDictionary *)imageMetaData{
    
    UIStoryboard *photoUploadStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCPhotoUploadVC *photoUploadVC=[photoUploadStory instantiateViewControllerWithIdentifier:@"PCPhotoUploadVC"];
    [photoUploadVC passImage:image withImageMetaDat:imageMetaData];
    
    [self.navigationController pushViewController:photoUploadVC animated:YES];
    
    simulationPressPlusBtn();
}

@end
